#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "cdefs.h"
#include "cbin.h"
#include "cmd5.h"

#define FAIL(str, line) {                       \
  printf("Fail on line %d: [%s]\n", line, str); \
  return str;                                   \
}

#define ASSERT(expr) {                  \
  static_num_tests++;                   \
  if (!(expr)) FAIL(#expr, __LINE__);   \
}

#define RUN_TEST(test) {        \
    const char *msg = test();   \
    if(msg)                     \
        return msg;             \
}


static int static_num_tests = 0;

const char *test_cmd5() {

	unsigned char hexdigest[33];

	bzero(hexdigest, sizeof(hexdigest));
	cmd5_hash(hexdigest, "", NULL);
	ASSERT(strcmp((char *)hexdigest, "d41d8cd98f00b204e9800998ecf8427e") == 0);

	bzero(hexdigest, sizeof(hexdigest));
	cmd5_hash(hexdigest, "The quick brown fox jumps over the lazy dog", NULL);
	ASSERT(strcmp((char *)hexdigest, "9e107d9d372bb6826bd81d3542a419d6") == 0);


	cmd5_ctx_t ctx;
	cmd5_init(&ctx);

	FILE *fp = NULL;
	unsigned char buf[4*1024];
	size_t nread;
	fp = fopen("cmd5.c", "r");
	ASSERT(fp != NULL);

	while((nread = fread(buf, 1, sizeof(buf), fp)) > 0)
	{
		cmd5_update(&ctx, buf, nread);
	}
	fclose(fp);

	cmd5_hexdigest(&ctx, hexdigest);

	ASSERT(strcmp((char *)hexdigest, "25e00cfdbc150f95a9e2cd82e1003b15") == 0);

    return NULL;
}


static const char *run_all_tests(void) {
    RUN_TEST(test_cmd5);
    return NULL;
}

int main(void) {
    const char *fail_msg = run_all_tests();
    printf("%s, tests run: %d\n", fail_msg ? "FAIL" : "PASS", static_num_tests);
    return fail_msg == NULL ? 0 : -1;
}

